package com.zhiwei.msf.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * function: spring工具类
 * author: zhiwei_yang
 * time: 2020/2/14-11:37
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 根据名称获取Bean
     *
     * @param beanName
     * @return
     */
    public static Object getBeanFromApplicationContext(String beanName) {
        if (StringUtils.isEmpty(beanName)) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据类型获取Bean
     *
     * @param beanClass
     * @return
     */
    public static <T> T getBeanFromApplicationContext(Class<T> beanClass) {
        if (null == beanClass) {
            return null;
        }
        return applicationContext.getBean(beanClass);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }
}
